package function;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class GrantPrivilege {

    private static final String SELECT = "SELECT";
    private static final String INSERT = "INSERT";
    private static final String UPDATE = "UPDATE";
    private static final String DELETE = "DELETE";
    //储存全部权限
    private static final List<String> ALL_PRIVILEGES = Arrays.asList(SELECT, INSERT, UPDATE, DELETE);


    public static void grantPrivilege(List<String> privileges, List<String> databaseTable, String name, String password) throws DocumentException, IOException {
        String database = databaseTable.get(1);
        String table = databaseTable.get(2);
        if (privileges.size() == 1 && privileges.get(0).equalsIgnoreCase("ALL")) {
            privileges = ALL_PRIVILEGES;
        }
        List<String> upperPrivileges = privileges.stream()
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        //输入中是否存在非法权限?
        boolean isLaw = upperPrivileges.stream().anyMatch(pri -> !ALL_PRIVILEGES.contains(pri));
        if (isLaw) {
            System.out.println("权限暂不存在!");
            return;
        }

        //验证请求登陆的用户信息
        Document document = new SAXReader().read("./mydatabase/user/user.xml");
        org.dom4j.Element node = (org.dom4j.Element) document.selectSingleNode("users/user[@name='" + name + "'and @password='" + password + "']");
        if (node == null) {
            System.out.println("无该用户!");
            return;
        }
        //获取用户的Id 操作其权限
        String id = node.attributeValue("id");
        Document roleDocument = new SAXReader().read("./mydatabase/user/roles.xml");
        Element roleElement = (Element) roleDocument.getRootElement().selectSingleNode("role[@id='" + id + "']");
        List<String> permissionsList = new ArrayList<>();

        //找出用户原有的权限,存到permissionsList
        if (roleElement != null) {
            List<Element> permissionsElement = roleElement.element("permissions").elements("permission");                // 获取permission元素
            for (Element permissionElement : permissionsElement) {
                permissionsList.add(permissionElement.getTextTrim());
            }
        }

        //找出upperPrivileges有而permissionsList没有的字符串。
        List<String> result = upperPrivileges.stream()
                .filter(permission -> !permissionsList.contains(permission))
                .collect(Collectors.toList());

        //写入文件
        for (String permission : result) {
            roleElement.element("permissions").addElement("permission").addText(permission);
        }
        File file = new File("./mydatabase/user/roles.xml");
        CreateTable.writeIO(file, roleDocument);

    }
}
